﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.LightSwitch;
namespace LightSwitchApplication
{
    public partial class SalesOrderItemRecipe
    {
        partial void RecipeDependency_Changed()
        {
            if (this.RecipeGroup != null && this.RecipeDependency != null && this.RecipeDependency.ChildProduct != null)
            {
                foreach (var itemRecipe in this.SalesOrderItem.ItemRecipes)//.Where(rec=>rec.RecipeGroup.Id==this.ParentRecipeGroup.Id)
                {
                    if (itemRecipe.ParentRecipeGroup != null && this.RecipeGroup != null && itemRecipe.ParentRecipeGroup.Id == this.RecipeGroup.Id)
                    {
                        if (itemRecipe.ParentRecipeProduct == null || (itemRecipe.ParentRecipeProduct != null && itemRecipe.ParentRecipeProduct.Id != this.RecipeDependency.ChildProduct.Id))
                        {
                            itemRecipe.ParentRecipeProduct = this.RecipeDependency.ChildProduct;
                            //itemRecipe.RecipeDependency = null;
                        }
                    }
                }
            }
        }

        partial void RecipePrice_Compute(ref decimal result)
        {
            result = (this.RecipeDependency != null && this.RecipeDependency.ChildProduct != null ? GetPrice(this.RecipeDependency.ChildProduct) : 0);
        }

        private decimal GetPrice(Product product)
        {
            decimal result = 0;
            if (product != null)
            {
                var productPrice = product.ProductPrices.Where(pr => pr.PriceDate <= this.SalesOrderItem.SalesOrder.OrderDate).OrderBy(pr => pr.PriceDate).LastOrDefault();
                if (productPrice != null)
                    result = productPrice.Price;
            }
            return result;
        }
    }
}
